package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisMessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @version V1.0
 * @author: luoqianjin
 * @date: 2019/8/4 14:44
 * @description: 手机验证码快速登录
 */
@RestController
@RequestMapping("login")
public class LoginController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;
    private Member member;

    /**
     * //使用手机号和验证码登录
     *
     * @return 1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
     * <p>
     * 2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
     * <p>
     * 3、向客户端写入Cookie，内容为用户手机号
     */
    @RequestMapping("check")
    public Result check(HttpServletResponse response, @RequestBody Map map) {
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();
        //从redis中获取缓存的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (codeInRedis == null || !validateCode.equals(codeInRedis)) {
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        } else {
            //验证码输入正确，判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            if (ObjectUtils.isEmpty(member)) {
                //当前用户不是会员，自动完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //登录成功
            //写入Cookie，跟踪用户
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//有效期30天
            response.addCookie(cookie);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
    }
}
